import React, {PureComponent, Fragment} from 'react';
import {findDOMNode} from 'react-dom';
import moment from 'moment';
import {connect} from 'dva';
import {List, Card, Row, Radio, Input, Badge, Button, Icon, Dropdown, Menu, Avatar, Modal, Form, message, Select, Table, Popconfirm,DatePicker,Tag
} from 'antd';
import MyPagination from '@/components/MyPagination';
import find from 'lodash/find'
import debounce from 'lodash/debounce'
import request from '@/utils/request';
import {ellipsis,download} from '@/utils/utils';
import ExportForm from './ExportForm'
import config from '../../config/config'
import Check from './check'
const FormItem = Form.Item;
const RadioButton = Radio.Button;

const RadioGroup = Radio.Group;
const Option = Select.Option;
const {Search, TextArea} = Input;
@connect(({applications, loading}) => ({
  applications,
  loading: loading.models.applications,
}))
@Form.create()
class BasicList extends PureComponent {
  constructor(props) {
    super(props);
    this.permissions = JSON.parse(sessionStorage.getItem('permissions'));
    this.state = {
      showAddBtn: find(this.permissions, {name: 'user_add_and_edit'}),
      showdelBtn: find(this.permissions, {name: 'user_delete'}),
      showPasswordBtn: find(this.permissions, {name: 'user_default_password_edit'}),
      user_password_reset: find(this.permissions, {name: 'user_password_reset'}),
      visible: false,
      done: false,
      page: 1,
      per_page: 30,
      username: '',
      editRecord: {},
      selectedRowKeys: [],
      banks:[]
    };
  }



  componentDidMount() {
    this.changeTableY()
    const {dispatch} = this.props;
    console.log('application')
    const {
      applications: {pageLoaded,scrollData},
    } = this.props;
    console.log('pageLoaded',pageLoaded)
    const table=document.querySelector('.ant-table-body')
    if(pageLoaded){
      setTimeout(function () {
        table.scrollTop = scrollData.y;
        table.scrollLeft = scrollData.x;
      },0)

    }else{
      const {
        applications: {searchParams},
      } = this.props;
      console.log('searchParams',searchParams)
      dispatch({
        type: 'applications/fetch',
        payload: searchParams,
        callback:()=>{
          const {dispatch} = this.props;
          dispatch({
            type: 'applications/changeLoaded',
          })
        }
      });
    }
    const that=this;

    window.addEventListener('resize', this.resize)
    table.addEventListener('scroll', debounce(this.scroll,150))
  }
  scroll=(e)=>{
    const {dispatch} = this.props;
    dispatch({
      type: 'applications/changeScroll',
      payload: {
        x:e.target.scrollLeft,
        y:e.target.scrollTop
      },
    })
  }
  resize = ()=> {
    this.changeTableY()
  }
  changeTableY=()=>{
    this.setState({
      tableY: document.querySelector('.table-pagination').getBoundingClientRect().top -
      document.querySelector('.custom-small-table').getBoundingClientRect().top -50
    })
  }

  componentWillUnmount() {
    console.log('componentWillUnmount')
    window.removeEventListener('resize', this.resize)
    const table=document.querySelector('.ant-table-body')
    table.removeEventListener('scroll', debounce(this.scroll,300))
  }
  handleSearch = (values, cb) => {
    console.log('handleSearch', values)
    const that = this;
    const {dispatch} = this.props;
    dispatch({
      type: 'applications/fetch',
      payload: {
        ...values,
      },
      callback: function () {
        console.log('handleSearch callback')
        if (cb) cb()
      }
    });
  }
  handleDelete = id => {
    const that = this;
    const {dispatch} = this.props;
    dispatch({
      type: 'applications/remove',
      payload: {id},
      callback: ()=> {
        message.success('删除申请成功')
        const {
          applications: {searchParams},
        } = that.props;
        that.handleSearch(searchParams);
      }
    });
  };
  handleAdd = ()=> {
    const formValues = this.AddUser.props.form.getFieldsValue();
    console.log('formValues', formValues)
    const that = this;
    this.props.dispatch({
      type: 'applications/add',
      payload: {
        ...formValues,
        role_id: formValues.role_id ? formValues.role_id.key : '',
      },
      callback: function () {
        message.success('新建用户成功')
        that.setState({
          addModal: false,
        });
        const {
          applications: {searchParams},
        } = that.props;
        that.handleSearch(searchParams);
      }
    });
  }
  handleEdit = ()=> {
    const formValues = this.EditUser.props.form.getFieldsValue();
    console.log('formValues', formValues)
    const that = this;
    this.props.dispatch({
      type: 'applications/edit',
      payload: {
        ...formValues,
        id: this.state.editRecord.id,
        status:formValues.status,
      },
      callback: function () {
        message.success('修改审核状态成功')
        that.setState({
          editModal: false,
        });
        const {
          applications: {searchParams},
        } = that.props;
        that.handleSearch(searchParams);
      }
    });
  }

  renderSimpleForm() {
    const {
      form: {getFieldDecorator},
      applications: {searchParams},
    } = this.props;
    return (
      <Form layout="inline" className="search-form">
        <FormItem label={'开始时间'}>
          {getFieldDecorator('started_at', {
            initialValue: moment(searchParams.started_at),
          })(
            <DatePicker
              style={{width:'120px'}}
              allowClear={false}
              //disabledDate={disabledDate}
              format="YYYY-MM-DD"
            />
          )}
        </FormItem>
        <FormItem label={'结束时间'}>
          {getFieldDecorator('ended_at', {
            initialValue: moment(searchParams.ended_at),
          })(
            <DatePicker
              style={{width:'120px'}}
              allowClear={false}
              //disabledDate={disabledDate}
              format="YYYY-MM-DD"
            />
          )}
        </FormItem>
        <FormItem label="车牌号码">
          {getFieldDecorator('license_plate_number', {
            initialValue: searchParams.license_plate_number,
          })(<Input    style={{width:'150px'}} placeholder="请输入"/>)}
        </FormItem>
        <FormItem label="车主手机">
          {getFieldDecorator('mobile', {
            initialValue: searchParams.mobile,
          })(<Input    style={{width:'150px'}} placeholder="请输入"/>)}
        </FormItem>
        <FormItem label={'状态'}>
          {getFieldDecorator('status',{
            initialValue:  '',
          })(
            <RadioGroup>
              <RadioButton value="">全部</RadioButton>
              <RadioButton value="2">审核通过</RadioButton>
              <RadioButton value="-1">审核不通过</RadioButton>
              <RadioButton value="1">正在审核</RadioButton>
            </RadioGroup>
          )}
        </FormItem>
        <FormItem >
          <Button type="primary" icon='search'  onClick={()=> {
            const {form} = this.props;
            form.validateFields((err, fieldsValue) => {
              if (err) return;

              this.handleSearch({
                page: 1,
                per_page: this.state.per_page,
                ...fieldsValue,
                started_at:  moment(fieldsValue.started_at).format('YYYY-MM-DD'),
                ended_at:  moment(fieldsValue.ended_at).format('YYYY-MM-DD'),
              })

            });
          }}>
            查询
          </Button>
          <Button style={{marginLeft: 8}}  icon='redo' onClick={this.handleFormReset}>
            重置
          </Button>
        <Button  className="btn-green" icon="export" style={{marginLeft: 8}} type="primary" onClick={
          ()=> {
            this.setState({
              exportModal: true
            })
          }
        }>
          导出EXCEL
        </Button>
        </FormItem>

      </Form>
    );
  }

  handleFormReset = () => {
    const {form} = this.props;
    form.resetFields();
    this.handleSearch({
      license_plate_number:'',
      mobile:'',
      status:'0',
      started_at:moment(new Date().getFullYear()+'-'+(parseInt(new  Date().getMonth())+1)+'-'+'01' , 'YYYY-MM-DD').format('YYYY-MM-DD'),
      ended_at: moment(new Date(), 'YYYY-MM-DD').format('YYYY-MM-DD'),
      page: 1,
      per_page: 30,
      bank_id:{
        key:'',
        label:''
      },
    })
  }
  exportCSV = ()=> {
    const that = this;
    const formValues = this.ExportformRef.props.form.getFieldsValue();
    console.log('formValues', formValues)
    const payload = {
      ...formValues,
      bank_id: formValues.bank_id?formValues.bank_id.key:'',
      started_at: moment(formValues.started_at).format('YYYY-MM-DD'),
      ended_at: moment(formValues.ended_at).format('YYYY-MM-DD'),
    }
    this.props.dispatch({
      type: 'applications/exportCSV',
      payload: payload,
      callback: function (download_key) {
        download(`${config.prefix}/admin/application_files?token=${`${sessionStorage.getItem('token')}`}&started_at=${payload.started_at}&ended_at=${payload.ended_at}&bank_id=${payload.bank_id}&license_plate_number=${payload.license_plate_number}&mobile=${payload.mobile}&status=${payload.status}`)
      }
    });
  }
  render() {
    const {
      applications: {data, loading, meta,searchParams,selectedRowKeys},
    } = this.props;
    const {
      form: {getFieldDecorator},
    } = this.props;
    const columns = [
      {
        title: '车牌号码',
        dataIndex: 'license_plate_number',
        fixed:'left',
        width: 100,
        render:(val)=>{
          return <Tag color="blue" style={{fontSize:'14px'}}>{val}</Tag>
        }
      },
      {
        title: '车主手机',
        width: 100,
        fixed:'left',
        dataIndex: 'mobile',
        render:(val)=>{
          return ellipsis(val,100)
        }
      },
      {
        title: '状态',
        dataIndex: 'status',
        width: 110,
        fixed:'left',
        render(val) {
          let type="", color="", text="";
          switch (val){
            case -1:
              type="close-circle", color="#eb2f96", text="审核不通过";
                  break
            case 1:
              type="info-circle", color="#7bc7ff", text="等待审核";
              break
            case 2:
              type="check-circle", color="#52c41a", text="审核通过";
              break
            default:
              break
          }
          return  <Fragment> <Icon type={type} theme="twoTone"  className="table-icon" twoToneColor={color}/>{text}</Fragment>
        },
      },
      {
        title: '申请时间',
        dataIndex: 'created_at',
        width: 150,
      },
      {
        title: '分销商头像/昵称',
        dataIndex: 'avatar_url',
        width: 120,
        render:(val,record)=> {
          return <div>
            <img className="table-avatar" src={record.distributor.avatar_url} alt=""/>{ ellipsis(record.distributor.nickname,70)}
            </div>
        }
      },
      {
        title: '分销商姓名',
        dataIndex: 'name',
        width: 90,
        render:(val,record)=>{
          return ellipsis(record.distributor.name,90)
        }
      },
      {
        title: '分销商手机',
        dataIndex: 'mobile2',
        width: 100,
        render:(val,record)=>{
          return  ellipsis(record.distributor.mobile,100)
        }
      },
      {
        title: '分销商层级',
        dataIndex: 'level',
        width: 100,
        render:(val,record)=>{
          return  ellipsis('层级'+record.distributor.level,100)
        }
      },
      {
        title: '审核时间',
        dataIndex: 'reviewed_at',
      },
      {
        title: '操作',
        width: 160,
        fixed:'right',
        render: (val, record, index) =>{
          return    <Fragment>
              <Button style={{marginRight: '8px'}} type="primary" icon='edit' size="small" onClick={(e)=> {
                e.stopPropagation()
                this.setState({
                  editRecord: record,
                  editModal: true
                })
              }
              }>审核</Button>
            <Popconfirm title={ '确定要删除吗?'}
                        onConfirm={(e)=>{
                          e.stopPropagation();this.handleDelete(record.id)
                        }}>
              <Button type="danger"  icon='delete'
                      size="small" onClick={(e)=>{ e.stopPropagation()}}>删除</Button>
            </Popconfirm>
          </Fragment>
        }
      },
    ];
    const rowSelection = {
      columnWidth:40,
      selectedRowKeys,
      columnTitle:' ',
      onChange:(selectedRowKeys) => {
        this.props.dispatch({
          type: 'applications/changeSelectRow',
          payload: selectedRowKeys,
        })
      },
    };
    return <div className="custom-card">
      <div className="table-title" >申请列表</div>
      <div className="table-page">
          <div className="table-condition">{this.renderSimpleForm()}</div>
          <Table
            style={{color: '#fff'}}
            className="custom-small-table"
            loading={loading}
            rowKey={'id'}
            dataSource={data}
            columns={columns}
            pagination={false}
            size="small"
            scroll={{x: 1400, y: this.state.tableY}}
            rowSelection={rowSelection}
            onRow={(record) => ({
              onClick: () => {
                this.props.dispatch({
                  type: 'applications/selectRow',
                  payload: record,
                })
              },
            })}
          />

      </div>
      <div className="table-pagination">
        <MyPagination searchCondition={{...searchParams}} meta={meta} handleSearch={this.handleSearch}/>
      </div>
      <Modal
        title={'审核 : ' + this.state.editRecord.license_plate_number }
        destroyOnClose
        visible={this.state.editModal}
        centered
        onOk={this.handleEdit}
        onCancel={()=> {
          this.setState({editModal: false, editRecord: {}})
        }}
      >
        <Check editRecord={this.state.editRecord}
                       wrappedComponentRef={(inst) => this.EditUser = inst}/>

      </Modal>
      <Modal
        title={'导出申请EXCEL'}
        visible={this.state.exportModal}
        centered
        onCancel={()=> {
          this.setState({exportModal: false})
        }}
        onOk={this.exportCSV}
      >
        <ExportForm banks={this.state.banks}  wrappedComponentRef={(inst) => this.ExportformRef = inst}/>

      </Modal>
    </div>
  }
}

export default BasicList;
